package com.neo.tiny.flowable.core.web;

import com.neo.tiny.admin.dto.user.SysUserDTO;
import com.neo.tiny.flowable.core.util.FlowableUtils;
import com.neo.tiny.secrity.model.AdminUserDetails;
import com.neo.tiny.secrity.util.SecurityUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @Description: flowable Web 过滤器，将 userId 设置到 {@link org.flowable.common.engine.impl.identity.Authentication} 中
 * @Author: yqz
 * @CreateDate: 2022/9/5 23:04
 */
public class FlowableWebFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        try {
            // 设置工作流的用户
            AdminUserDetails user = SecurityUtils.getUser();

            Long userId = Optional.ofNullable(user)
                    .map(AdminUserDetails::getSysUser)
                    .map(SysUserDTO::getId).orElse(null);
            if (userId != null) {
                FlowableUtils.setAuthenticatedUserId(userId);
            }
            // 过滤
            chain.doFilter(request, response);
        } finally {
            // 清理
            FlowableUtils.clearAuthenticatedUserId();
        }
    }
}